package com.wulian.common.controller;

import com.wulian.common.constants.CommonConstants;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.util.JSONUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 
* @ClassName: BaseController 
* @Description: TODO(父类Controller,提供request,response,session注入.feign接口不支持request参数传递时候,继承这个父类.) 
* @author 马志豪
* @date 2019年9月11日 下午5:03:09 
* 
* @param <T>
 */
public class BaseController<T> {
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	
	@Autowired
    StringRedisTemplate redisTemplate;

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
	}

	protected String getJson(Object obj) {
		return JSONUtil.toJSON(obj);
	}

	/**
	 * 获取当前用户信息
	 */
	protected UserInfo getCurrentUser(){
		String token = getFromRequest(request, CommonConstants.USER_TOKEN);
		if (StringUtils.isBlank(token)) {
			logger.error("token为空");
			return null;
		}

		try {
			token = URLDecoder.decode(token, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("解析token报错 {}", e.getMessage());
		}
		String userInfoJson = redisTemplate.opsForValue().get(CommonConstants.USER_TOKEN_PREFIEX + token);

		if (StringUtils.isNotBlank(userInfoJson)) {
			UserInfo user = JSONUtil.fromJSON(userInfoJson, UserInfo.class);
			return user;
		} else {
			logger.error("获取当前用户信息异常");
			return null;
		}
	}
	/**
	 * 获取当前用户信息
	 */
	protected UserInfo getCurrentUserByApp(String userToken){
		String token = userToken;

		try {
			token = URLDecoder.decode(token, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("解析token报错 {}", e.getMessage());
		}
		String userInfoJson = redisTemplate.opsForValue().get(CommonConstants.USER_TOKEN_PREFIEX + token);

		if (StringUtils.isNotBlank(userInfoJson)) {
			UserInfo user = JSONUtil.fromJSON(userInfoJson, UserInfo.class);
			return user;
		} else {
			logger.error("获取当前用户信息异常");
			return null;
		}
	}

	/**
	 * 
	* @Title: getFromRequest 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param request
	* @param @param paramName
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws 
	* @author 马志豪
	* @date 2019年9月16日 上午11:30:48 
	* @version V1.0
	 */
	private static String getFromRequest(HttpServletRequest request, String paramName) {
        String value = request.getParameter(paramName);
        if (StringUtils.isBlank(value)) {
            value = request.getHeader(paramName);
            if (StringUtils.isBlank(value)) {
                if (request.getCookies() != null) {
                    for (Cookie cookie : request.getCookies()) {
                        if (cookie.getName().equals(paramName)) {
                            value = cookie.getValue();
                        }
                    }
                }
            }
        }
        return value;
    }
	
	
}
